#include "configRequest.h"
#include "heartRequest.h"

char **getewayIp;
gchar *sn = NULL;

char *getGatewayIp()
{
    if (getewayIp != NULL)
    {
        return getewayIp;
    }
    
    //1.读取当前文件目录下面的config.ini  获取 devinfo_path 地址
    GKeyFile *configiniPath=g_key_file_new();
    if(!g_key_file_load_from_file(configiniPath,"./config.ini",G_KEY_FILE_NONE,NULL)){
      g_warning("load config.ini error!");
      return NULL;
    }
    gchar *path =g_key_file_get_string(configiniPath,"config","path",NULL);
    g_key_file_free(configiniPath);

    //2.去devinfo_path指定的文件中读取 ip 和 地址
    GKeyFile *configPath =  g_key_file_new();
    if(!g_key_file_load_from_file(configPath,path,G_KEY_FILE_NONE,NULL)){
      g_warning("load config.ini error!");
      return NULL;
    }
    gchar *gatewayIp= g_key_file_get_string(configPath,"config","ip",NULL);
    g_key_file_free(configPath);

    printf("gatewayIp:%s\n",gatewayIp);

    return gatewayIp;
}

//缓存sn
gchar *getDiviceSn()
{
//    if (sn!=NULL)
//    {
//       return sn;
//    }
//    FILE *file = fopen("/sys/class/dmi/id/product_serial","r");
//    char *sn = (char*)calloc(1,256); 
//    //读取一行数据
//    fgets(sn,256,file);
//    fclose(file);
//    g_print("sn=%s\n",sn);
   return "jfjjfjfjjfjfjfjf";
}

//等待来着消息队列的消息，收到消息后发送配置请求
void *revcMsgAndSendConfig(void* param){
    while (1)
    {
        printf("wait boa  msg:\n");
        int mqId = getMsgQueue(PATHNAME_BOA_MAIN,PROCESS_ID_BOA_MAIN);
        if (mqId==-1)
        {
            perror("create mq error");
            pthread_exit(NULL);
        }
        Message msg={
        
        };
        int recSize = recvMsg(mqId,&msg,MSG_SIZE);
        if (recSize==-1)
        {
            perror("recv msg error");
        }
        //发送请求
        printf("接收数据成功\n");

        sendConfigRequest();

    }
}

int main(int argc, char const *argv[])
{

    //新打开一个线程用来接收mq消息 发送配置信息
    pthread_t tid;
    pthread_create(&tid,NULL,revcMsgAndSendConfig,NULL);

    //每5秒钟 发送一个心跳请求
    while(1){
        char *ip = getGatewayIp();
        printf("jdjdjdj:%s\n",ip);
        char *sn = getDiviceSn();
        sleep(5);
        sendHeartRequest(ip, sn);
        
    }
        
    return 0;
}
